package com.itheima.tlias08_14.utils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.util.Date;

public class JwtUtil {
    private final static String KEY = "b5d0e4c3-2cb8-44c7-a0b5-499e2a1a2a2f";

    private JwtUtil() {

    }


    /**
     * 创建一个临时的token
     *
     * @param username
     * @param password
     * @param minutes
     * @return token
     */
    public static String createTemporaryToken(String username, String password, long minutes) {
        //1、请求jwt对象
        JwtBuilder jwt = Jwts.builder();
        //2、指定header信息(通常不指定)
        //3、指定payload信息
        //往payload信息中添加用户信息
        Date now = new Date();
        jwt.claim("username", username)
                .claim("password", password)
                .issuedAt(now)
                .expiration(new Date(now.getTime() + minutes * 60 * 1000));
        //4、进行数字化签名信息
        jwt.signWith(Keys.hmacShaKeyFor(KEY.getBytes()), Jwts.SIG.HS256);
        //生成token
        String token = jwt.compact();
        return token;

    }

    public static JSONObject decode(String token) {
        //解析token整体
        //1.构建Jwt解析对象
        JwtParser parser = Jwts.parser().verifyWith(Keys.hmacShaKeyFor(KEY.getBytes())).build();
        //2.指定数字签名
        //3.指定token
        Claims payload = parser.parseSignedClaims(token).getPayload();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", payload.get("username"));
        jsonObject.put("password", payload.get("password"));
        jsonObject.put("生效时间：", payload.getIssuedAt());
        jsonObject.put("失效时间：", payload.getExpiration());
        return jsonObject;
    }
}
